package com.zengchen.content.feignclient.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class TokenTransferInterceptor implements RequestInterceptor {
    /**
     * Called for every request. Add data using methods on the supplied {@link RequestTemplate}.
     *  将 WX-TOKEN 传递到下一个请求里
     * @param template
     */
    @Override
    public void apply(RequestTemplate template) {
        // 1.从请求的Header里取出token
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = attributes.getRequest();
        String token = request.getHeader("WX-TOKEN");
        // 2.存入token
        if(StringUtils.isNotBlank(token)){
            template.header("WX-TOKEN",token);
        }
    }
}
